package oop.ex3.filemanager;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.LinkedList;

import oop.ex3.nameserver.SessionThread;
import oop.ex3.protocol.ClientMessageSender;

public class UploadRequestThread extends Thread{

	private static final int TIMEOUT_5_SECONDS = 5000;
	
	private FileManager _fileManager;
	private ServerSocket _requestSocket;
	private LinkedList<UploadThread> _uploadThreads;
	
	//TODO javadoc
	public UploadRequestThread(FileManager fileManager){
		this._fileManager=fileManager;
		this._requestSocket=fileManager.getRequestSocket();
		this._uploadThreads = new LinkedList<UploadThread>();
	}
	
	public void run(){
		Socket clientSocket;
		while (!_requestSocket.isClosed()){
			
			try{
				clientSocket=_requestSocket.accept();
				clientSocket.setSoTimeout(TIMEOUT_5_SECONDS);
				DataInputStream input = new DataInputStream(clientSocket.getInputStream());
				DataOutputStream output = new DataOutputStream(clientSocket.getOutputStream());
				if (!(input.readUTF().equals(ClientMessageSender.WANT_FILE))){
					ClientMessageSender.error(output);
					input.close();
					output.close();
					clientSocket.close();
					continue;
				}
				String fileName = input.readUTF();
				if (!(input.readUTF().equals(ClientMessageSender.END))){
					ClientMessageSender.error(output);
					input.close();
					output.close();
					clientSocket.close();
					continue;
				}
				
				//get connection details - add reading
				UploadThread newUpload = new UploadThread
								(_fileManager, clientSocket, fileName); //add name Parameter
				_fileManager.addUploader(newUpload);
				newUpload.start();
				
			}catch (SocketTimeoutException e1){
				//timeout, restarting requestSocket.
				_fileManager.restartRequestSocket();
				System.out.println("RequestSocket Timed Out...");
			}catch (IOException e2){
				System.out.println("FileManager has been Shut-Down...");
				//serverSocket cannot accept a new connection - it's closed
				break;
			}
		}
		
		return; //TODO only return?
		
	}
}
